<template>
  <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
    <!-- 表单区域 -->
    <a-form :model="form" layout="inline" class="header">
      <a-row :gutter="[16, 16]">
        <a-col :span="8">
          <a-form-item label="售后单号">
            <a-input v-model="form.shoppid" placeholder="请输入"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="用户昵称">
            <a-input v-model="form.shoppinfo" placeholder="请输入"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="退款方式">
            <a-select v-model="form.shoppsouse" placeholder="请选择" style="width: 182px" disabled>
              <a-select-option value="余额">余额</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="售后类型">
            <a-select v-model="form.paywayf" placeholder="请选择" style="width: 182px">
              <a-select-option value="整单售后">整单售后</a-select-option>
              <a-select-option value="部分商品售后">部分商品售后</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="售后状态">
            <a-select v-model="form.paystat" placeholder="请选择" style="width: 182px">
              <a-select-option value="全部">全部</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="订单状态">
            <a-select v-model="form.shopstat" placeholder="请选择" style="width: 182px">
              <a-select-option value="已取消">已取消</a-select-option>
              <a-select-option value="已完成">已完成</a-select-option>
              <a-select-option value="待发货">待发货</a-select-option>
              <a-select-option value="待付款">待付款</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-space>
            <a-button type="primary" @click="checkshopinfo">查询</a-button>
            <a-button @click="hadrest">重置</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>

    <!-- Tab栏 -->
    <a-tabs :active-key="defaultActiveKey" @change="handleChange" style="margin-top: 20px;">
      <a-tab-pane key="all" :tab="`全部（${dataSource.length}）`"></a-tab-pane>
      <a-tab-pane key="selling" :tab="`售后中（${sellingCount}）`"></a-tab-pane>
      <a-tab-pane key="success" :tab="`售后成功（${successCount}）`"></a-tab-pane>
      <a-tab-pane key="failed" :tab="`售后关闭（${failedCount}）`"></a-tab-pane>
    </a-tabs>

    <!-- 表格 -->
    <a-table
        :columns="columns"
        :data-source="filteredDataSource"
        :pagination="pagination"
        row-key="id"
        :loading="loading"
    >
      <!-- 商品信息列 -->
      <template slot="skuImage" slot-scope="text, record">
        <a-avatar :src="record.skuImage" shape="square" style="width: 50px; height: 50px;"/>
        <span>{{ record.goodsname }}</span>
      </template>

      <!-- 自定义 operate 列的内容 -->
      <template slot="operate" slot-scope="text, record">
        <a-space>
          <a-button v-if="record.afterStatus === '售后中'" type="link" @click="viewafter(record)">同意售后</a-button>
          <a-button v-if="record.afterStatus === '售后中'" type="link" @click="viewremafter(record)">拒绝售后</a-button>

          <!-- 更多按钮 -->
          <a-dropdown>
            <a-button type="link">
              更多
            </a-button>
            <a-menu slot="overlay">
              <a-menu-item @click="viewDetails(record)">订单备注</a-menu-item>
            </a-menu>
          </a-dropdown>
        </a-space>
      </template>
    </a-table>

    <!-- 仅退款的模态框 -->
    <a-modal v-model="isRefundModalVisible" title="订单备注" @cancel="handleCancelRefund" :footer="null">
      <!-- 备注输入框 -->
      <a-textarea
          v-model="refundRemarks"
          rows="4"
          placeholder="请输入备注"
          style="margin-bottom: 20px"
      />

      <!-- 底部按钮区 -->
      <a-space>
        <a-button type="primary" @click="handleSaveRefundRemarks">确定</a-button>
      </a-space>
    </a-modal>


    <!-- 退货退款的模态框 -->
    <a-modal v-model="isReturnModalVisible" title="退货退款详细信息" @cancel="handleCancelReturn" :footer="null">
      <div class="order-image">
        <a-avatar :src="currentRecord ? currentRecord.skuImage : ''" shape="square"
                  style="width: 100px; height: 100px;"/>
      </div>
      <div>
        <p><strong>售后单号：</strong>{{ currentRecord ? currentRecord.afterSn : '' }}</p>
        <p><strong>商品名称：</strong>{{ currentRecord ? currentRecord.goodsname : '' }}</p>
        <p><strong>售后类型：</strong>{{ currentRecord ? currentRecord.refundType : '' }}</p>
        <p><strong>售后状态：</strong>{{ currentRecord ? currentRecord.afterStatus : '' }}</p>
      </div>
      <!-- 如果找到默认地址，显示其信息 -->
      <div v-if="defaultAddress" style="margin: 30px 0">
        <h3>默认地址信息</h3>
        <p><strong>收件人：</strong>{{ defaultAddress.contact }}</p>
        <p><strong>手机号：</strong>{{ defaultAddress.mobile }}</p>
        <p><strong>地址：</strong>{{ defaultAddress.provinceId }} {{ defaultAddress.cityId }}
          {{ defaultAddress.districtId }} {{ defaultAddress.info }}</p>
      </div>
      <div v-else>
        <p>没有默认地址</p>
      </div>
      <!-- 发货方式选择 -->
      <div style="margin: 0 0 20px 0">
        <strong>发货方式：</strong>
        <a-radio-group v-model="shippingMethod">
          <a-radio value="express">快递配送</a-radio>
          <a-radio value="no-logistics">无需物流</a-radio>
        </a-radio-group>
      </div>

      <!-- 物流公司选择 -->
      <div v-if="shippingMethod === 'express'" style="margin: 0 0 50px 0">
        <strong>物流公司：</strong>
        <a-select v-model="selectedLogisticsCompany" placeholder="请选择物流公司" style="width: 100px">
          <a-select-option v-for="company in logisticsCompanies" :key="company" :value="company">
            {{ company }}
          </a-select-option>
        </a-select>
        <a-input v-model="manualLogisticsCompany" placeholder="请输入物流单号" style="width: 200px; margin-top: 10px;"/>
      </div>
      <!-- 底部按钮区 -->
      <a-space style="float: right;height: 5px">
        <a-button @click="handleCancelReturn">取消</a-button>
        <a-button type="primary" @click="handleShip">发货</a-button>
      </a-space>
    </a-modal>

    <!-- 备注模态框 -->
    <a-modal
        v-model="isShipModalVisible"
        title="备注"
        @cancel="handleShipCancel"
        @ok="shipqqOrder()"
        :width="800"
        class="ship-order-modal"
    >
      <div class="ship-order">
        <div class="order-info">
            <p><strong>备注：</strong>{{ Remark }}</p>
        </div>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import axios from "axios";
import Cookie from "js-cookie";

export default {
  data() {
    return {
      defaultActiveKey: 'all', // 默认选中的 Tab 键
      form: {
        shoppid: '', // 售后单号
        shoppinfo: '', // 用户昵称
        shoppsouse: undefined, // 退款方式
        paywayf: undefined, // 售后类型
        paystat: undefined, // 售后状态
        shopstat: undefined, // 订单状态
      },
      dataSource: [],
      filteredDataSource: [],
      columns: [
        {title: '售后单号', dataIndex: 'afterSn', id: 'afterSn'},
        {title: '买家昵称', dataIndex: 'username', id: 'username'},
        {title: '商品信息', dataIndex: 'goodsname', id: 'goodsname', scopedSlots: {customRender: 'skuImage'}},
        {title: '数量', dataIndex: 'num', id: 'num'},
        {title: '退款金额', dataIndex: 'refundMoney', id: 'refundMoney'},
        {title: '售后类型', dataIndex: 'refundType', id: 'refundType'},
        {title: '售后状态', dataIndex: 'afterStatus', id: 'afterStatus'},
        {title: '申请时间', dataIndex: 'createTime', id: 'createTime'},
        {title: '操作', id: 'operate', scopedSlots: {customRender: 'operate'}}
      ],
      pagination: {
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      loading: false,
      selectedRowKeys: [], // 用于存储选中的行键
      isRefundModalVisible: false, // 仅退款模态框
      isReturnModalVisible: false, // 退货退款模态框
      currentRecord: {},
      refundRemarks: '这是仅退款订单的备注信息...',
      userAddress: null,  // 用户地址信息
      defaultAddress: null,  // 默认地址
      shippingMethod: 'express', // 发货方式
      selectedLogisticsCompany: '', // 物流公司选择
      logisticsCompanies: ['顺丰快递', '中通快递'], // 物流公司列表
      manualLogisticsCompany: '',//物流单号
      isShipModalVisible: false,
      Remark: null,
    };
  },
  mounted() {
    this.fetchOrderAfterInfo();
    if (this.logisticsCompanies.length > 0) {
      this.selectedLogisticsCompany = this.logisticsCompanies[0]; // 默认选择第一个物流公司
    }
  },
  created() {
    this.filteredDataSource = [...this.dataSource];
  },
  methods: {
    viewDetails(data) {
      console.log(data)
      this.Remark = data.refundRemark
      this.isShipModalVisible = true
    },

    handleShipCancel() {
      this.isShipModalVisible = false
    },

    shipqqOrder() {
      this.isShipModalVisible = false
    },

    remoteafter() {
      // 准备要发送的数据
      const data = {
        aftersn: this.currentRecord.afterSn,  // 使用当前记录的售后单号
        expressname: '',  // 物流公司
        expressno: '',  // 物流单号
        handleid: Cookie.get('auth_id'),  // 操作员ID，假设为1
        handleremark: '审核失败，拒绝售后',  // 备注信息
        afterstatus: '售后失败',  // 售后状态改为“售后失败”
      };
      this.fetchup(data)
    },
    handleSaveRefundRemarks() {
      // 准备要发送的数据
      const data = {
        aftersn: this.currentRecord.afterSn,  // 使用当前记录的售后单号
        expressname: '',  // 物流公司
        expressno: '',  // 物流单号
        handleid: Cookie.get('auth_id'),  // 操作员ID，假设为1
        handleremark: this.refundRemarks ? this.refundRemarks : '',  // 备注信息
        afterstatus: '售后成功',  // 售后状态改为“售后成功”
      };
      this.fetchup(data)
    },
    async handleShip() {
      // 准备要发送的数据
      const data = {
        aftersn: this.currentRecord.afterSn,  // 使用当前记录的售后单号
        expressname: this.selectedLogisticsCompany ? this.selectedLogisticsCompany : "",  // 物流公司
        expressno: this.manualLogisticsCompany ? this.manualLogisticsCompany : '',  // 物流单号
        handleid: Cookie.get('auth_id'),  // 操作员ID，假设为1
        handleremark: '审核通过，等待发货',  // 备注信息
        afterstatus: '售后成功',  // 售后状态改为“售后成功”
      };
      this.fetchup(data)
    },
    async fetchup(data) {
      try {
        // 发送POST请求
        const response = await axios.post(`${window.location.protocol}//${window.location.hostname}:8080/api/orderafter/updatestatus`, data, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token'),  // 认证 token
          },
        });

        // 请求成功
        if (response.data.code === 200) {
          location.reload()

          // 关闭模态框
          this.isReturnModalVisible = false;

        } else {
          this.$message.error('发货操作失败：' + response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
        this.$message.error('发货操作失败，网络错误');
      }
    },
    async fetchUserAddressInfo() {
      try {
        const userId = this.currentRecord.userId;
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/address/info?userId=${userId}`, {
          headers: {Authorization: `Bearer ` + localStorage.getItem('token')}
        });
        if (response.data.code === 200) {
          const addressData = response.data.data;
          this.userAddress = addressData.reverse();
          this.defaultAddress = addressData.find(address => address.isDefault === 1);
        }
      } catch (error) {
        console.error('获取用户地址信息失败:', error);
      }
    },

    viewremafter(record) {
      this.currentRecord = record;
      this.remoteafter()
    },

    viewafter(record) {
      this.currentRecord = record;
      if (this.currentRecord.afterStatus === '售后中') {
        if (record.refundType === '仅退款') {
          this.refundRemarks = '这是仅退款订单的备注信息...';
          this.isRefundModalVisible = true;
        } else if (record.refundType === '退货退款') {
          this.isReturnModalVisible = true;
        }
        this.fetchUserAddressInfo();
      }
    },

    handleCancelRefund() {
      this.isRefundModalVisible = false;
    },

    handleCancelReturn() {
      this.isReturnModalVisible = false;
    },

    async fetchOrderAfterInfo() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/orderafter/infoorderafterall`, {
          headers: {Authorization: `Bearer ` + localStorage.getItem('token')}
        });
        if (response.data.code === 200) {
          let orderAfterData = response.data.data;
          // 遍历订单数据，设置 username
          orderAfterData.forEach(item => {
            item.username = item.username == null || item.username === "" ? "乐购" + (item.addressMobile ? item.addressMobile.slice(-4) : '') : item.username;
          });
          this.dataSource = orderAfterData;
          this.filteredDataSource = [...this.dataSource];
          this.pagination.total = this.dataSource.length;
          this.filterData();
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },

    checkshopinfo() {
      this.filterData();
    },

    hadrest() {
      this.form = {
        shoppid: '',
        shoppinfo: '',
        shoppsouse: undefined,
        paywayf: undefined,
        paystat: undefined,
        shopstat: undefined,
      };
      this.filterData();
    },

    handleChange(activeKey) {
      this.defaultActiveKey = activeKey;
      this.filterData();
    },

    filterData() {
      let filtered = [...this.dataSource];
      if (this.form.shoppid) {
        filtered = filtered.filter(item => item.afterSn.includes(this.form.shoppid));
      }
      if (this.form.shoppinfo) {
        filtered = filtered.filter(item => item.username.includes(this.form.shoppinfo));
      }
      if (this.form.shoppsouse !== undefined) {
        filtered = filtered.filter(item => item.addressContact === this.form.shoppsouse);
      }
      if (this.form.paywayf !== undefined) {
        filtered = filtered.filter(item => item.refundType === this.form.paywayf);
      }
      if (this.form.paystat !== undefined) {
        filtered = filtered.filter(item => item.afterStatus === this.form.paystat);
      }
      if (this.form.shopstat !== undefined) {
        filtered = filtered.filter(item => item.afterStatus === this.form.shopstat);
      }
      if (this.defaultActiveKey === 'selling') {
        filtered = filtered.filter(item => item.afterStatus === '售后中');
      } else if (this.defaultActiveKey === 'success') {
        filtered = filtered.filter(item => item.afterStatus === '售后成功');
      } else if (this.defaultActiveKey === 'failed') {
        filtered = filtered.filter(item => item.afterStatus === '售后失败');
      }
      this.filteredDataSource = filtered;
    },

    handleDelete(record) {
      const index = this.dataSource.findIndex(item => item.id === record.id);
      if (index !== -1) {
        this.dataSource.splice(index, 1);
        this.filterData();
      }
    },
  },

  computed: {
    sellingCount() {
      return this.dataSource.filter(item => item.afterStatus === '售后中').length;
    },
    successCount() {
      return this.dataSource.filter(item => item.afterStatus === '售后成功').length;
    },
    failedCount() {
      return this.dataSource.filter(item => item.afterStatus === '售后关闭').length;
    },
  },
};
</script>

<style scoped>
.header {
  margin-bottom: 20px;
}
</style>
